package br.com.simora.component;

import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;

import br.com.caelum.vraptor.AroundCall;
import br.com.caelum.vraptor.InterceptionException;
import br.com.caelum.vraptor.Intercepts;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.controller.ControllerMethod;
import br.com.caelum.vraptor.interceptor.SimpleInterceptorStack;
import br.com.simora.controller.HomeController;

@Intercepts
@RequestScoped
public class AcessInterceptor {
	 @Inject private Result result;
	 @Inject private AcessSession session;
	 @Inject private ControllerMethod method;
	 @Inject protected ResourceBundle bundle;
	 private List<String> errors;
	 
	@AroundCall
	public void intercept(SimpleInterceptorStack stack) throws InterceptionException {
		if((session == null || session.getNome() == null) 
				&& !method.getMethod().getName().contains("login")
				&& !method.getMethod().getName().contains("entrar")
				&& !method.getMethod().getName().contains("cadastro")
				&& !method.getMethod().getName().contains("gravar")
				&& !method.getMethod().getName().contains("pagar")
				&& !method.getMethod().getName().contains("indexAdmin")
				&& !method.getMethod().getName().contains("indexUsuario")
				&& !method.getController().getType().getName().contains("Home")){
				errors = new ArrayList<String>();
				errors.add(bundle.getString("alert.login.necessario"));
				result.include("error", errors);
				result.redirectTo(HomeController.class).index();
			} else {
				stack.next();
			}
	}
	
	private Boolean isMethodsForbidden(){
		if(method.getMethod().getName().contains("indexAdmin") || method.getMethod().getName().contains("indexUsuario")){
			return true;
		}
		return false;
	}
	
	private Boolean isHomeController(){
		return method.getController().getType().getName().contains("Home");
	}
	
	private Boolean isCadastroController(){
		return method.getController().getType().getName().contains("Cadastro");
	}

}